//
//  News.m
//  SimulationTechnologyHeadlines
//
//  Created by 移云 on 2019/10/17.
//  Copyright © 2019 admin. All rights reserved.
//

#import "News.h"

@implementation News

- (instancetype)initWithDic:(NSDictionary *)dic
{
    if (self = [super init])
    {
        [self setValuesForKeysWithDictionary:dic];
    }
    return self;
}

+ (instancetype)newsWithDic:(NSDictionary *)dic
{
    return [[self alloc]initWithDic:dic];
}


//没有相应的键值互对的时候，避免奔溃
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    
}

+ (void)requestNewsDataWithPage:(int)page AndSuccess:(void (^)(NSArray * _Nonnull))success AndError:(void (^)(NSString *_Nonnull))error
{
    NSString *urlStr = [NSString stringWithFormat:@"http://kjtt.wokeji.com/index/push-arcs?access-token=KzYDcKOAPkM4b2snv2EHdstYrkTLTw6u&page=%d&sort=1",page];
    
//    NSLog(@"%@",urlStr);
    //该地址尽管是XML数据，但是请求返回的是个字典
    NSURL *url = [NSURL URLWithString:urlStr];
    
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15];
    [request setValue:@"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Mobile Safari/537.36" forHTTPHeaderField:@"User-Agent"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
         if (!connectionError)
                {
                    //判断是否正常接受服务器放回的数据
                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
                    if (httpResponse.statusCode == 200 || httpResponse.statusCode ==304)
                    {
                        //data - 二进制数据 是JSON 形式的字符串
                        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//                        NSLog(@"%@",str);
   
                        
                        // 将字符串转换成字典
                        NSData * getJsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:NULL];
                       
                        //字典转模型
                        NSArray *arrayDic = getDict[@"data"];

                        //调用成功回调
                        success(arrayDic.copy);
                        
                    }else{
                        error(@"服务器内部错误");
                    }
                    
                }else{
                    error(@"网络出小差了");
    
                }
        
    }];
}


@end
